package fti.uksw.ruang;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import fti.uksw.ruang.fragment.AddEventFragment;
import fti.uksw.ruang.fragment.AddEventFragment.AddEventFragmentListener;
import fti.uksw.ruang.fragment.AddRoomFragment;
import fti.uksw.ruang.fragment.AddRoomFragment.AddRoomFragmentListener;
import fti.uksw.ruang.model.CalendarEvent;
import fti.uksw.ruang.model.CalendarList;
import fti.uksw.ruang.model.Dosen;
import fti.uksw.ruang.model.Guest;
import fti.uksw.ruang.model.Login;
import fti.uksw.ruang.model.MsgCode;
import fti.uksw.ruang.model.Pengguna;
import fti.uksw.ruang.model.RecurringDetail;
import fti.uksw.ruang.websocket.ClientListener;
import fti.uksw.ruang.websocket.WebSocketClient;

public class NewItemAct extends ActionBarActivity implements
		AddEventFragmentListener, AddRoomFragmentListener, ClientListener {

	private static final String TAG = NewItemAct.class.getName();

	public static final String TAG_EDIT_EVENT = "edit_event";

	FragmentManager fm;
	FragmentTransaction ft;

	boolean insertCalendarList = false;
	boolean insertEvent = false;
	private CalendarEvent event;
	private CalendarList calendarList;
	private Login login;
	private ArrayList<Dosen> listDosen;

	private Button btnSave;
	private Button btnCancel;

	private WebSocketClient wsClient = LoginActivity.wsClient;
	private ClientListener cl;
	private AddEventFragment addEventFragment;

	private AddRoomFragment addRoomFragment;
//	private SharedPreferences prefs;

	private boolean edit = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newitem);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setTitle("Lab's Calendar");
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.show();

		btnSave = (Button) findViewById(R.id.okcancelbar_ok);
		btnCancel = (Button) findViewById(R.id.okcancelbar_cancel);
		btnSave.setOnClickListener(btnOkClickListener);
		btnCancel.setOnClickListener(btnCancelClickListener);

		cl = this;
		wsClient.addListener(cl);

		// set ActionBar
		ActionBar ab = getSupportActionBar();
		ab.setDisplayShowTitleEnabled(true);

		login = (Login) getIntent().getExtras().get(Login.TAG);
		ab.setSubtitle(login.getUsername());

		sendRequestRoom();
		sendRequestDosen();

		// show add event fragment first
		addEventFragment = new AddEventFragment();
		manageFragment(addEventFragment, AddEventFragment.TAG);
		
		edit = getIntent().getBooleanExtra(TAG_EDIT_EVENT, false);
		if(edit){
			event = (CalendarEvent) getIntent().getExtras().get(CalendarEvent.TAG);
			Toast.makeText(this, "edit event", Toast.LENGTH_SHORT).show();
		}
	}

	
	private void sendRequestDosen() {
		JSONObject msgReq = new JSONObject();
		try {
			msgReq.put(MsgCode.MSGCODE, MsgCode.DOSENREQ);
			wsClient.sendTextMessage(msgReq.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void sendRequestRoom() {
		JSONObject msg = new JSONObject();
		try {
			msg.put(MsgCode.MSGCODE, MsgCode.CALENDARLISTREQ);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		wsClient.sendTextMessage(msg.toString());
	}

	private OnClickListener btnOkClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			boolean moveToCalView = false;
			if (insertEvent) {
				JSONObject msgRes = new JSONObject();
				try {
					JSONObject jsonEvent = new JSONObject();
					jsonEvent.put(CalendarEvent.CALENDARID,
							event.getCalendarId());
					jsonEvent.put(CalendarEvent.COLOR, event.getColor());
					jsonEvent.put(CalendarEvent.DESCRIPTION,
							event.getDescription());
					jsonEvent.put(CalendarEvent.ENDTIME, event.getEndTime()
							.getTime());
					jsonEvent.put(CalendarEvent.ISALLDAYEVENT,
							event.getIsAllDayEvent());
					jsonEvent.put(CalendarEvent.LOCATION, event.getLocation());
					jsonEvent.put(CalendarEvent.OPERATORID,
							event.getOperatorId());
					jsonEvent.put(CalendarEvent.RECURRINGRULE,
							event.getRecurringRule());
					jsonEvent.put(CalendarEvent.STARTTIME, event.getStartTime()
							.getTime());
					jsonEvent.put(CalendarEvent.SUBJECT, event.getSubject());
					jsonEvent.put(CalendarEvent.EVENTID, event.getSubject());

					if (event.getRecurringRule() == CalendarEvent.FLAG) {
						JSONObject jsonRd = new JSONObject();
						RecurringDetail rd = event.getRecurringDetail();
						jsonRd.put(RecurringDetail.INTERVAL, rd.getInterval());
						jsonRd.put(RecurringDetail.TYPE, rd.getType());
						jsonRd.put(RecurringDetail.UNTIL, rd.getUntil()
								.getTime());
						jsonEvent.put(RecurringDetail.TAG, jsonRd);
					}

					JSONObject jsonGuest = new JSONObject();
					Guest g = event.getGuest();
					jsonGuest.put(Guest.IDDOSEN, g.getIdDosen());
					jsonEvent.put(Guest.TAG, jsonGuest);

					JSONObject jsonPengguna = new JSONObject();
					Pengguna p = event.getPengguna();
					jsonPengguna.put(Pengguna.NAMA, p.getNama());
					jsonPengguna.put(Pengguna.NOTELP, p.getNoTelp());
					jsonEvent.put(Pengguna.TAG, jsonPengguna);

					msgRes.put(MsgCode.MSGCODE, MsgCode.ADDEVENTREQ);
					msgRes.put(CalendarEvent.TAG, jsonEvent);
					wsClient.sendTextMessage(msgRes.toString());
					Log.d(TAG, msgRes.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				moveToCalView = true;
			} else if (insertCalendarList) {
				JSONObject msg = new JSONObject();
				try {
					msg.put(MsgCode.MSGCODE, MsgCode.ADDCALENDARLISTREQ);
					msg.put(CalendarList.CALENDARTITLE,
							calendarList.getCalendarTitle());
					msg.put(CalendarList.CALENDARID,
							calendarList.getCalendarId());
					msg.put(CalendarList.JENIS, calendarList.getJenis());
					msg.put(CalendarList.KAPASITAS, calendarList.getKapasitas());
					Log.d(TAG, msg.toString());
					wsClient.sendTextMessage(msg.toString());
					moveToCalView = true;
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (moveToCalView) {
				Intent intentCalView = new Intent(v.getContext(),
						CalViewAct.class);
				intentCalView.putExtra(Login.TAG, login);
				startActivity(intentCalView);
				wsClient.removeListener(cl);
				finish();
			}
		}
	};

	private OnClickListener btnCancelClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intentCalView = new Intent(v.getContext(), CalViewAct.class);
			intentCalView.putExtra(Login.TAG, login);
			startActivity(intentCalView);
			wsClient.removeListener(cl);
			finish();
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.new_item_menu, menu);
		return true;
	}

	private void manageFragment(Fragment fragment, String tag) {
		fm = getSupportFragmentManager();
		ft = fm.beginTransaction();
		ft.replace(R.id.newitem_container, fragment, tag);
		// ft.addToBackStack(null);
		ft.commit();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.add_room) {
			addRoomFragment = new AddRoomFragment();
			manageFragment(addRoomFragment, AddRoomFragment.TAG);
			sendRequestRoom();
		} else if (item.getItemId() == R.id.add_schedule) {
			addEventFragment = new AddEventFragment();
			manageFragment(addEventFragment, AddEventFragment.TAG);
			sendRequestRoom();
			sendRequestDosen();
		}

		return true;
	}

	@Override
	public void itemEvent(CalendarEvent mCe) {
		event = mCe;
		insertEvent = true;
		insertCalendarList = false;
	}

	@Override
	public void itemRoom(CalendarList mCl) {
		calendarList = mCl;
		insertEvent = false;
		insertCalendarList = true;
	}

	@Override
	public void onConnect(String message) {

	}

	private ArrayList<CalendarList> calList;

	private void setListRoom() {
		addEventFragment = (AddEventFragment) getSupportFragmentManager()
				.findFragmentByTag(AddEventFragment.TAG);
		if (addEventFragment != null) {
			addEventFragment.setRooms(calList);
		} else {
			addRoomFragment = (AddRoomFragment) getSupportFragmentManager()
					.findFragmentByTag(AddRoomFragment.TAG);
			if (addRoomFragment != null) {
				addRoomFragment.setRooms(calList);
			}
		}
	}

	private void setListDosen() {
		addEventFragment = (AddEventFragment) getSupportFragmentManager()
				.findFragmentByTag(AddEventFragment.TAG);
		if (addEventFragment != null) {
			addEventFragment.setDosen(listDosen);
		}
	}

	@Override
	public void onMessage(String message) {
		Log.d(TAG, message);
		try {
			JSONObject msg = new JSONObject(message);
			String msgCode = msg.getString(MsgCode.MSGCODE);
			if (msgCode.equals(MsgCode.CALENDARLISTRES)) {
				calList = new ArrayList<CalendarList>();
				JSONArray arrJson = msg.getJSONArray(CalendarList.TAG);
				for (int i = 0; i < arrJson.length(); i++) {
					JSONObject jsonCalList = arrJson.getJSONObject(i);
					CalendarList _cl = new CalendarList();
					_cl.setId(jsonCalList.getInt(CalendarList.ID));
					_cl.setCalendarId(jsonCalList
							.getString(CalendarList.CALENDARID));
					_cl.setCalendarTitle(jsonCalList
							.getString(CalendarList.CALENDARTITLE));
					_cl.setJenis(jsonCalList.getString(CalendarList.JENIS));
					_cl.setKapasitas(jsonCalList.getInt(CalendarList.KAPASITAS));
					calList.add(_cl);
				}
				setListRoom();
			} else if (msgCode.equals(MsgCode.DOSENRES)) {
				listDosen = new ArrayList<Dosen>();
				JSONArray arrJsonDosen = msg.getJSONArray(Dosen.TAG);
				for (int i = 0; i < arrJsonDosen.length(); i++) {
					JSONObject jsonDosen = arrJsonDosen.getJSONObject(i);
					Dosen _d = new Dosen();
					_d.setEmail(jsonDosen.getString(Dosen.EMAIL));
					_d.setId(jsonDosen.getInt(Dosen.ID));
					_d.setJenisKelamin(jsonDosen.getString(Dosen.JENISKELAMIN));
					_d.setNama(jsonDosen.getString(Dosen.NAMA));
					_d.setNotelp(jsonDosen.getString(Dosen.NOTELP));
					listDosen.add(_d);
				}
				setListDosen();
			} else if (msgCode.equals(MsgCode.MSGCONFIRM)) {

				Toast.makeText(this, msg.getString(MsgCode.MSGCONTENT),
						Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(byte[] data) {
		// Log.d(TAG, "Byte msg : " + new String(data));
	}

	@Override
	public void onDisconnect(String reason) {
		Toast.makeText(this, "Disconnect from server", Toast.LENGTH_LONG)
				.show();
		logout(getWindow().getDecorView().findViewById(android.R.id.content));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (wsClient.isConnected()) {
			Log.d(TAG, "remove client");
			wsClient.removeListener(this);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			wsClient.removeListener(this);
			Intent intentCalView = new Intent(getApplicationContext(),
					CalViewAct.class);
			intentCalView.putExtra(Login.TAG, login);
			startActivity(intentCalView);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void logout(View v) {
		wsClient.removeListener(this);
		wsClient.closeConnection();
		Intent i = new Intent(v.getContext(), LoginActivity.class);
		v.getContext().startActivity(i);
		finish();
	}

	@Override
	public void onError(Exception error) {

	}

}
